<?php

/**
 * Class CommodityPlusOne_Model
 */
class CommodityPlusOne_Model extends CI_Model
{
    /**
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    public static function getAllResultArray(){
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity_plus_one.*');
        $CI->db->from('commodity_plus_one');

        $query  = $CI->db->get();
        $result = $query->result();

        return $result;
    }

    /**
     * @param int $commodityId
     * @param int $userId
     * @return bool
     */
    public static function toggleCommodityPlusOne($commodityId, $userId)
    {
        if (self::isCommodityPlusOneExist($commodityId, $userId)) {
            self::deleteCommodityPlusOne($commodityId, $userId);
            return false;
        } else {
            self::addCommodityPlusOne($commodityId, $userId);
            return true;
        }
    }

    /**
     * @param int $commodityId
     * @param int $userId
     * @return bool
     */
    public static function addCommodityPlusOne($commodityId, $userId)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $result = $CI->db->insert('commodity_plus_one', array('commodity_id' => $commodityId, 'user_id' => $userId));

        if ($result)
            return true;
        else
            return false;
    }


    /**
     * @param int $commodityId
     * @param int $userId
     * @return bool
     */
    public static function deleteCommodityPlusOne($commodityId, $userId)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->where('commodity_plus_one.commodity_id', $commodityId);
        $CI->db->where('commodity_plus_one.user_id', $userId);

        $result = $CI->db->delete('commodity_plus_one');
        if ($result)
            return true;
        else
            return false;
    }

    /**
     * @param int $commodityId
     * @return mixed
     */
    public static function countCommodityPlusOneByCommodityId($commodityId)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity_plus_one.id');
        $CI->db->from('commodity_plus_one');
        $CI->db->where('commodity_plus_one.commodity_id', $commodityId);

        return $CI->db->get()->num_rows();
    }

    /**
     * @param int $commodityId
     * @param int $userId
     * @return bool
     */
    public static function isCommodityPlusOneExist($commodityId, $userId)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity_plus_one.id');
        $CI->db->from('commodity_plus_one');
        $CI->db->where('commodity_plus_one.commodity_id', $commodityId);
        $CI->db->where('commodity_plus_one.user_id', $userId);

        if ($CI->db->get()->num_rows())
            return true;
        else
            return false;
    }
}
